/*
 * @Author: liu
 * @Date: 2024-04-28 00:14:23
 * @LastEditors: liu
 * @LastEditTime: 2024-04-29 01:20:18
 * @FilePath: \yyx_ser_ts\app\controller\UploadController.ts
 * @Description:
 * 天道酬勤
 */

import { Context, Next } from 'koa'
import path from 'path'
import OSS from 'ali-oss'
import config from '../config'

import response from '../../utils/response'
import {
  ChapterException,
  GetCourseException,
  UpdateChapterException,
  UploadImgrException
} from '../exception/HttpException'
import { get, post, controller, use, unifyUse } from '../router/decorator/index'

const client = new OSS({
  region: config.oss.region,
  accessKeyId: config.oss.accessKeyId as string,
  accessKeySecret: config.oss.accessKeySecret as string,
  bucket: config.oss.bucket
})

/** 装饰器router class */
export type RouterController<T extends string> = {
  [key in T]: (ctx: Context) => Promise<void>
}

type MethodName = 'getName' | 'postName'

@controller('/')
//@unifyUse<MethodName>(commonMiddleware)
class UploadController {
  //新增课程接口
  @post('/aliUpload')
  async aliUpload(ctx: Context, next: Next) {
    //文件上传后,上传的信息被放在ctx.request.files中，
    //console.log(ctx.request.files)
    try {
      if (ctx.request.files) {
        // @ts-ignore
        const { file } = ctx.request.files
        console.log(file)

        let date = new Date()
        let time =
          '' + date.getFullYear() + (date.getMonth() + 1) + date.getDate()
        let filepath = 'course/' + time + '/' + date.getTime()
        // @ts-ignore
        let fileext = file.filepath.split('.').pop()
        let newfile = filepath + '.' + fileext
        console.log(newfile)
        // @ts-ignore
        const res1 = await client.put(newfile, file.filepath)

        //获取带加密签名的图片路径，注意这里的路径不能带有bucket
        //let imgUrl = client.signatureUrl(newfile)
        let imgUrl = res1.url

        let data = {
          course_img: imgUrl
        }

        response.success(ctx, data, '图片上传成功')
      }
    } catch (err) {
      throw new UploadImgrException(err, '图片上传异常!', 401)
    }
  }
}

export default new UploadController()
